<template>
  <div>
    <BasicCard>
      <BasicVxeForm ref="formRef" :formOptions="formOptions" :clearable="false" @search="getData">
        <template #personDocumentList="{ data, field }">
          <RenYuanModal
            ref="renYuanModalRef"
            v-model="data[field]"
            v-model:gongZhongID="data['gongZhongID']"
            :gongZhongOptions="gongZhongOptions"
            :gongXuOptions="gongXuOptions"
            :formData="formOptions.data!"
            @confirm="getData"
          />
        </template>
      </BasicVxeForm>
    </BasicCard>

    <BasicCard>
      <BasicVxeTable v-bind="statisticsGridOptions"> </BasicVxeTable>
    </BasicCard>

    <BasicCard>
      <BasicVxeTable v-bind="statisticsByMaterialGridOptions"> </BasicVxeTable>
    </BasicCard>

    <BasicCard>
      <BasicVxeTable v-bind="detailGridOptions"> </BasicVxeTable>
    </BasicCard>
  </div>
</template>

<script setup lang="ts">
  import {
    getCurrentAndLastBanCi,
    getQuYuOptions,
    getListItem,
    splitTsIdToTime,
    convertTimeUnit,
    formatNumber
  } from '@/utils'
  import { calcFooter, transformSumFields } from '@/components/ui/vxe-table'
  import RenYuanModal from './components/RenYuanModal.vue'
  import { type FormV0, columns, sumFields } from './data'
  import { postRenYuanJiaoXiao_XS, postYuanGongJiXiaoList } from '@/api/personAdmin'
  import { getJiChuBaoBiaoGongXu } from '@/api/gongGongChaXun'
  import { getGongZhongHuoQu } from '@/api/gongGongChaXun'

  const props = defineProps<{
    isQuYu: boolean
  }>()

  const renYuanModalRef = ref<InstanceType<typeof RenYuanModal>>()

  // 区域
  const quYuOptions = ref<LabelValueOption[]>([])
  // 工序
  const gongXuOptions = ref<LabelValueOption[]>([])
  // 班次
  const shiftOptions = ref<LabelValueOption[]>([])
  // 工种
  const gongZhongOptions = ref<LabelValueOption[]>([])

  const showTablesLoading = () => {
    statisticsGridOptions.loading = true
    statisticsByMaterialGridOptions.loading = true
    detailGridOptions.loading = true
  }

  const hideTablesLoading = () => {
    statisticsGridOptions.loading = false
    statisticsByMaterialGridOptions.loading = false
    detailGridOptions.loading = false
  }

  const clearTablesData = () => {
    statisticsGridOptions.data = []
    statisticsByMaterialGridOptions.data = []
    detailGridOptions.data = []
  }

  // 获取工艺节点list
  const getGongXuBuDaiFuJi = async () => {
    await getJiChuBaoBiaoGongXu().then((res) => {
      gongXuOptions.value = res.map((v) => ({ ...v, label: v.name, value: v.id }))
      formOptions.data!.gongXuId =
        gongXuOptions.value.find((v) => v.label === '细纱')?.value || gongXuOptions.value[0].value
    })
  }

  // 获取tsIdSelect选择器的数据和选项
  const getTsIdSelect = async () => {
    const banCiOpt = await getCurrentAndLastBanCi(
      props.isQuYu ? formOptions.data!.quYuValue : formOptions.data!.gongXuId,
      { isQy: props.isQuYu, isGetLast: true }
    )

    formOptions.data!.tsIdSelect = banCiOpt.banCiInfo
    shiftOptions.value = banCiOpt.shiftOptions

    await renYuanModalRef.value?.init()

    getData()
  }

  // 获取工种列表
  const getGongZhongList = () => {
    getGongZhongHuoQu('').then((val) => {
      const options = val.map((item) => {
        return { label: item.title, value: item.id }
      })
      gongZhongOptions.value = options
    })
  }

  // 工序变化时
  const handleGongXuChange = () => {
    const { gongXuId } = formOptions.data!
    const gongXuName = getListItem(gongXuOptions.value, gongXuId)?.label

    if (gongXuName) {
      showTablesLoading()
      clearTablesData()
      if (['细纱', '络筒', '末并'].includes(gongXuName)) {
        statisticsGridOptions.columns = columns[gongXuName]['staff']['statisticsColumns']
        statisticsByMaterialGridOptions.columns =
          columns[gongXuName]['staff']['statisticsByMaterialColumns']
        detailGridOptions.columns = columns[gongXuName]['staff']['detailColumns']
      } else {
        statisticsGridOptions.columns = columns['default']['staff']['statisticsColumns']
        statisticsByMaterialGridOptions.columns =
          columns['default']['staff']['statisticsByMaterialColumns']
        detailGridOptions.columns = columns['default']['staff']['detailColumns']
      }

      getTsIdSelect()
    }
  }

  const formatDate = (date: string | number) => {
    return convertTimeUnit(date, 's', 'm')
  }

  // 获取员工绩效列表
  const getData = async () => {
    try {
      showTablesLoading()
      const { tsIdSelect, gongXuId, personDocumentList, gongZhongID } = formOptions.data!
      const { startTsId, endTsId } = tsIdSelect
      let data = {
        tsIdStart: startTsId,
        tsIdEnd: endTsId,
        jobTitleId: gongZhongID,
        // TODO: 不知道 111 是什么东西
        craftNodeId: gongXuId === '111' ? '' : gongXuId,
        personDocumentList: personDocumentList
      }

      const gongXuName = getListItem(gongXuOptions.value, gongXuId)?.label

      statisticsGridOptions.data = []
      statisticsByMaterialGridOptions.data = []
      detailGridOptions.data = []

      if (gongXuName === '细纱') {
        await postRenYuanJiaoXiao_XS(data).then((res) => {
          statisticsGridOptions.data = res.statistics.map((v) => ({
            ...v,
            breakCntToNext: formatNumber(v.breakCntToNext),
            jointTimeAvg: formatDate(v.jointTimeAvg),
            doffingTimeAvg: formatDate(v.doffingTimeAvg),
            efcRun: formatNumber(v.efcRun),
            // classLength: formatNumber(v.classLength),
            actualYarnWeight: formatNumber(v.actualYarnWeight, 1),
            doffingCnt: formatNumber(v.doffingCnt, 0),
            stopTime: formatDate(v.stopTime),
            yarnLength: formatNumber(v.yarnLength),
            stopTimeAvg: formatDate(v.stopTimeAvg)
          }))

          statisticsByMaterialGridOptions.data = res.statisticsByMaterial.flatMap((v) =>
            v.byPersonMaterial.flatMap((vv) => ({
              personDocumentId: v.personDocumentId,
              personName: v.personName,
              materialId: vv.materialId,
              materialName: vv.materialName,
              scanCnt: vv.scanCnt,
              yarnLength: vv.yarnLength == formatNumber(vv.yarnLength),
              breakCntToNext: formatNumber(vv.breakCntToNext),
              jointTimeAvg: formatDate(vv.jointTimeAvg),
              doffingTimeAvg: formatDate(vv.doffingTimeAvg),
              efcRun: formatNumber(vv.efcRun),
              // classLength: vv.classLength == null ? vv.classLength : parseInt(vv.classLength),
              actualYarnWeight: formatNumber(vv.actualYarnWeight),
              doffingCnt: formatNumber(vv.doffingCnt, 0),
              stopTime: formatDate(vv.stopTime),
              stopTimeAvg: formatDate(vv.stopTimeAvg)
            }))
          )

          detailGridOptions.data = res.detail.flatMap((v) =>
            v.byTsidPerson.flatMap((vv) =>
              vv.byTsidPersonMaterial.flatMap((vvv) => ({
                dateTimeStr: splitTsIdToTime(v.tsId) + v.shiftName,
                tsId: v.tsId,
                shiftName: v.shiftName,
                teamSet: v.teamSet,
                yarnLength_hj: formatNumber(v.yarnLength),
                theoreticalYarnWeight_hj: formatNumber(v.theoreticalYarnWeight),
                actualYarnWeight_hj: formatNumber(v.actualYarnWeight, 1),
                stopTime_hj: formatDate(v.stopTime),
                stopTimeAvg: formatDate(v.stopTimeAvg),
                personDocumentId: vv.personDocumentId,
                personName: vv.personName,
                materialId: vvv.materialId,
                materialName: vvv.materialName,
                scanCnt: vvv.scanCnt,
                jointTimeAvg: formatDate(vvv.jointTimeAvg),
                breakCntToNext: formatNumber(vvv.breakCntToNext),
                doffingCnt: formatNumber(vvv.doffingCnt, 0),
                doffingTimeAvg: formatDate(vvv.doffingTimeAvg),
                efcRun: formatNumber(vvv.efcRun),
                stopTime: formatDate(vvv.stopTime),
                yarnLength: formatNumber(vvv.yarnLength),
                theoreticalYarnWeight: formatNumber(vvv.theoreticalYarnWeight, 0),
                actualYarnWeight: formatNumber(vvv.actualYarnWeight, 1)
              }))
            )
          )
        })
      } else {
        await postYuanGongJiXiaoList(data).then((res) => {
          statisticsGridOptions.data = res.statistics.map((v) => ({
            ...v,
            efcRun: formatNumber(v.efcRun),
            // classLength: formatNumber(v.classLength, 0),
            actualYarnWeight: formatNumber(v.actualYarnWeight, 1),
            // jointTimeRound: formatNumber(v.jointTimeRound, 0),
            stopTime: formatDate(v.stopTime),
            stopTimeAvg: formatDate(v.stopTimeAvg),
            warningCnt: v.warningCnt,
            durationTotal: convertTimeUnit(v.durationTotal, 'ms', 'm')
          }))

          statisticsByMaterialGridOptions.data = res.groupdatas.flatMap((v) =>
            v.byPersonMaterial.flatMap((vv) => ({
              personDocumentId: v.personDocumentId,
              personName: v.personName,
              materialId: vv.materialId,
              materialName: vv.materialName,
              scanCnt: vv.scanCnt,
              efcRun: formatNumber(vv.efcRun),
              yarnLength: formatNumber(vv.yarnLength),
              actualYarnWeight: formatNumber(vv.actualYarnWeight, 1),
              theoreticalYarnWeight: formatNumber(vv.theoreticalYarnWeight, 0),
              stopTime: formatDate(vv.stopTime),
              stopTimeAvg: formatDate(vv.stopTimeAvg),
              warningCnt: vv.warningCnt,
              durationTotal: convertTimeUnit(vv.durationTotal, 'ms', 'm')
            }))
          )

          detailGridOptions.data = res.detaildatas.flatMap((v) =>
            v.byTsidPerson.flatMap((vv) =>
              vv.byTsidPersonMaterial.flatMap((vvv) => ({
                dateTimeStr: splitTsIdToTime(v.tsId) + v.shiftName,
                tsId: v.tsId,
                shiftName: v.shiftName,
                teamSet: v.teamSet,
                yarnLength_hj: formatNumber(v.yarnLength),
                theoreticalYarnWeight_hj: formatNumber(v.theoreticalYarnWeight),
                actualYarnWeight_hj: formatNumber(v.actualYarnWeight, 1),
                stopTime_hj: formatDate(v.stopTime),
                stopTimeAvg: formatDate(v.stopTimeAvg),
                personDocumentId: vv.personDocumentId,
                personName: vv.personName,
                materialId: vvv.materialId,
                materialName: vvv.materialName,
                scanCnt: vvv.scanCnt,
                efcRun: formatNumber(vvv.efcRun),
                yarnLength: formatNumber(vvv.yarnLength),
                actualYarnWeight: formatNumber(vvv.actualYarnWeight, 1),
                theoreticalYarnWeight: formatNumber(vvv.theoreticalYarnWeight, 0),
                stopTime: formatDate(vvv.stopTime),
                warningCnt: vvv.warningCnt,
                durationTotal: convertTimeUnit(vvv.durationTotal, 'ms', 'm')
              }))
            )
          )
        })
      }
    } catch (err) {
      console.log(err)
    } finally {
      hideTablesLoading()
    }
  }

  const formRef = ref<BasicFormInstance<FormV0>>()
  const formOptions = reactive<BasicFormProps<FormV0>>({
    data: { gongZhongID: '' } as FormV0,
    titleWidth: 60,
    items: [
      {
        field: 'quYuValue',
        title: '区域',
        visibleMethod: () => props.isQuYu,
        itemRender: {
          name: 'ElSelect',
          options: computed(() => quYuOptions.value) as unknown as LabelValueOption[],
          props: { style: 'width: 100px' },
          events: {
            change: () => {
              getTsIdSelect()
            }
          }
        }
      },
      {
        field: 'gongXuId',
        itemRender: {
          name: 'ElSelect',
          options: computed(() => gongXuOptions.value) as unknown as LabelValueOption[],
          props: { style: 'width: 100px' },
          events: {
            change: () => {
              handleGongXuChange()
            }
          }
        }
      },
      {
        field: 'tsIdSelect',
        itemRender: {
          name: 'ShiftSchedulePicker',
          props: {
            shiftOptions: computed(() => shiftOptions.value) as unknown as LabelValueOption[]
          }
        }
      },
      {
        field: 'personDocumentList',
        title: '人员',
        slots: {
          default: 'personDocumentList'
        }
      },
      {
        field: 'form-actions',
        itemRender: {
          name: 'ActionButtons',
          children: [{ name: 'search' }]
        }
      }
    ]
  })

  const statisticsGridOptions = reactive<BasicGridProps>({
    extraConfig: {
      title: '人员绩效报表',
      isCustom: true,
      isExport: true,
      isFilterAndSort: true
    }, // 拓展的配置
    id: `personAdmin-jiXiaoKaoHao-YuanGongView-statistics`, // id用于缓存,务必配置
    maxHeight: 480,
    columns: columns['细纱']['staff']['statisticsColumns'],
    toolbarConfig: {}, // 工具栏
    exportConfig: {
      filename: '绩效考核_按人员'
    },
    showFooter: true,
    footerMethod: calcFooter({
      ...transformSumFields(sumFields),
      personName: {
        formatter: () => '合计'
      }
    })
  })

  const statisticsByMaterialGridOptions = reactive<BasicGridProps>({
    extraConfig: {
      title: '分品种统计',
      isCustom: true,
      isExport: false,
      isFilterAndSort: true
    }, // 拓展的配置
    id: `personAdmin-jiXiaoKaoHao-YuanGongView-statisticsByMaterialMachine`, // id用于缓存,务必配置
    maxHeight: 480,
    columns: columns['细纱']['staff']['statisticsByMaterialColumns'],
    toolbarConfig: {} // 工具栏
  })

  const detailGridOptions = reactive<BasicGridProps>({
    extraConfig: {
      title: '班次详细报表',
      isCustom: true,
      isExport: false,
      isFilterAndSort: true
    }, // 拓展的配置
    id: `personAdmin-jiXiaoKaoHao-YuanGongView-detail`, // id用于缓存,务必配置
    maxHeight: 480,
    columns: columns['细纱']['staff']['detailColumns'],
    toolbarConfig: {} // 工具栏
  })

  onMounted(async () => {
    await getGongXuBuDaiFuJi()
    await getGongZhongList()
    // 有区域先拿区域 再用区域选项第一个去拿班次
    if (props.isQuYu) {
      quYuOptions.value = await getQuYuOptions()
      formOptions.data!.quYuValue = quYuOptions.value[0].value
    }
    await getTsIdSelect()
  })
</script>

<style lang="scss" scoped></style>
